<template>
    <slot :value="tweeningValue" :thousandsValue="toThousands(tweeningValue)">
        <template v-if="thousands">{{toThousands(tweeningValue)}}</template>
        <template v-else>{{tweeningValue}}</template>
    </slot>
</template>

<script>
    export default {
        name: 'AnimatedInteger',
        components: {
            
        },
        props: {
            value: {
                type: Number,
                required: true
            },
            thousands:{
                type:Boolean,
            }
        },
        data() {
            return {
               tweeningValue: 0,
               animationTiming:800,
               requestAnimationFrameId:null,
            }
        },
        watch: {  //监听器
            value: function (newValue, oldValue) {
                cancelAnimationFrame(this.requestAnimationFrameId);
                this.tween(parseFloat(this.tweeningValue), newValue);
            }
        },
        methods: {
            tween(startValue, endValue) {
                let {
                    animationTiming
                } = this;
                let startTime = new Date().valueOf();
                let animate = () =>  {
                    let currentTime = new Date().valueOf();
                    let scheduleTime = currentTime - startTime;
                    this.tweeningValue = ((scheduleTime / animationTiming) * (endValue - startValue) + startValue).toFixed(0);
                    if(endValue - startValue > 0 ? this.tweeningValue >= endValue : this.tweeningValue <= endValue){
                        this.tweeningValue = endValue;
                    }else{
                        this.requestAnimationFrameId = requestAnimationFrame(animate);
                    }
                }
                animate();
            },
            toThousands(num) {
                return (num || 0).toString().replace(/(?<=^\d*)(\d)(?=(?:\d{3})+(?:[^\d].+)?$)/g, '$1,');
            },
        },
        created() {

        }, //组件实例创建完成，属性已绑定，但DOM还未生成，属性还不存在
        mounted(){
            this.tween(0, this.value);
        }, //模板编译/挂载之后(不保证组件已在document中)
//        beforeCreate(){}, //组件实例刚被创建，组件属性计算之前，如data属性等
//        created(){}, //组件实例创建完成，属性已绑定，但DOM还未生成，属性还不存在
//        beforeMount(){}, //模板编译/挂载之前
//        beforeUpdate(){}, //组件更新之前
//        updated(){}, //组件更新之后
//        activated(){}, //for keep-alive,组件被激活时调用
//        deactivated(){}, //for keep-alive,组件被激活时调用
//        beforeDestory(){}, //组件销毁前调用
//        destoryed(){}, //组件销毁后调用
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
